<template>
  <a-drawer
    :title="'报价单明细'"
    :width="1200"
    :open="visibleFlag"
    @close="onClose"
    :destroyOnClose="true"
    :body-style="{ paddingBottom: '80px' }"
  >
<!--
  <a-modal
    title="报价单明细"
    :width="1200"
    :open="visibleFlag"
    @cancel="onClose"
    :maskClosable="false"
    :destroyOnClose="true"
  >
-->
    <a-row class="smart-table-btn-block">
      <div class="smart-table-operate-block">
        <a-button  type="primary" @click="addItem(1)">
          <template #icon>
            <PlusOutlined />
          </template>
          添加主材
        </a-button>
        <a-button  type="primary" @click="addItem(3)">
          <template #icon>
            <PlusOutlined />
          </template>
          添加配件
        </a-button>
        <a-button  type="primary" danger :disabled="selectedRowKeyList.length === 0" @click="onDelete">
          <template #icon>
            <DeleteOutlined />
          </template>
          批量删除
        </a-button>
      </div>
<!--      <div class="smart-table-setting-block">-->
<!--        <TableOperator v-model="columns" :tableId="null" :refresh="queryData" />-->
<!--      </div>-->
      <a-alert :message="quotationDetail.templateName" type="info" show-icon />

    </a-row>
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 5 }" >
      <a-table
          size="small"
          :scroll="{ y: 1000 }"
          :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange, getCheckboxProps: getCheckboxProps }"
          :dataSource="tableData"
          :columns="columns"
          :rowKey="(record,index)=>{return index}"
          :bordered="true"
          :loading="tableLoading"
          :pagination="false"
      >
<!--
          :row-selection="{ selectedRowKeys: selectedRowKeyList, onChange: onSelectChange }"
-->
        <template #bodyCell="{ text, record, index, column }">
<!--          品名-->
          <template v-if="column.dataIndex === 'productName'">
            <a-form-item :name="column.dataIndex" class="form-item-no-margin">
              <a-input style="width: 100%" v-model:value="record.productName" :placeholder="column.title"
                       :disabled="record.type !== 1 && record.type !== 3"/>
            </a-form-item>
          </template>
<!--          规格-->
          <template v-if="column.dataIndex === 'specifications'">
            <a-form-item :name="column.dataIndex"  class="form-item-no-margin">
              <a-input style="width: 100%" v-model:value="record.specifications" :placeholder="column.title"
                       :disabled="record.type !== 1 && record.type !== 3"/>
            </a-form-item>
          </template>
<!--          比重-->
          <template v-if="column.dataIndex === 'specificWeight'">
            <a-form-item  :name="column.dataIndex" class="form-item-no-margin">
              <a-input-number style="width: 100%" v-model:value="record.specificWeight" :placeholder="column.title"
                              :disabled="record.type !== 1" min="0" :precision="2" @change="value => handleInputChange(value, index)"/>
            </a-form-item>
          </template>
<!--          用量-->
          <template v-if="column.dataIndex === 'usagee'">
            <a-form-item :name="column.dataIndex" class="form-item-no-margin">
              <a-input-number style="width: 100%" v-model:value="record.usagee" :placeholder="column.title"
                              min="0" @change="value => handleInputChange(value, index)"/>
            </a-form-item>
          </template>
<!--          单价-->
          <template v-if="column.dataIndex === 'unitPrice'">
            <a-form-item :name="column.dataIndex" class="form-item-no-margin">
              <a-input-number style="width: 100%" v-model:value="record.unitPrice" :placeholder="column.title"
                              min="0" @change="value => handleInputChange(value, index)" />
            </a-form-item>
          </template>
<!--          金额-->
          <template v-if="column.dataIndex === 'sumOfMoney'">
            <a-form-item :name="column.dataIndex" class="form-item-no-margin">
              <a-input-number style="width: 100%" v-model:value="record.sumOfMoney" :placeholder="column.title"
                              min="0" />
            </a-form-item>
          </template>
<!--          备注-->
          <template v-if="column.dataIndex === 'remark'">
            <a-form-item :name="column.dataIndex" class="form-item-no-margin">
              <a-input style="width: 100%" v-model:value="record.remark" :placeholder="column.title" />
            </a-form-item>
          </template>
        </template>
      </a-table>

    </a-form>

    <div
        :style="{
        position: 'absolute',
        right: 0,
        bottom: 0,
        width: '100%',
        borderTop: '1px solid #e9e9e9',
        padding: '10px 16px',
        background: '#fff',
        textAlign: 'right',
        zIndex: 1,
      }"
    >
      <a-button style="margin-right: 8px" @click="onClose">取消</a-button>
      <a-button type="primary" @click="onSubmit">提交</a-button>
    </div>
  </a-drawer>
</template>

<script setup>
  import { reactive, ref, nextTick } from 'vue';
  import _ from 'lodash';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import { quotationTemplateApi } from '/@/api/business/template/quotation-template-api';
  import { smartSentry } from '/@/lib/smart-sentry';

  const visibleFlag = ref(false);
  let templateId = 0
  let quotationDetail

  function show(rowData) {
    Object.assign(form, formDefault);
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    // 使用字典时把下面这注释修改成自己的字典字段 有多个字典字段就复制多份同理修改 不然打开表单时不显示字典初始值
    // if (form.status && form.status.length > 0) {
    //   form.status = form.status.map((e) => e.valueCode);
    // }
    visibleFlag.value = true;
    quotationDetail = rowData
    templateId = rowData.templateId
    nextTick(() => {
      formRef.value.clearValidate();
    });
    queryItems()
  }

  function onClose() {
    Object.assign(form, formDefault);
    visibleFlag.value = false;
  }

  // 组件ref
  const formRef = ref();

  const formDefault = {
    templateLong: undefined, //长
    templateHeight: undefined, //高度
    templateName: undefined, //报价单名称
    disabledFlag: undefined, //禁用状态
    remark: undefined, //备注
  };

  let form = reactive({ ...formDefault });

  const rules = {
    // productName: [{ required: true, message: '品名 必填' }],
  };
  // 表格数据
  let resultTableColumns = ref();

  const columns = ref([
    // {
    //   title: '#',
    //   dataIndex: 'rowIndex',
    //   width: 30,
    //   ellipsis: true,
    //   align: 'center',
    //   customRender: function (text, r, index) {
    //     return (text !== '总计') ? (parseInt(index) + 1) : text
    //   }
    // },
    {
      title: '品名',
      dataIndex: 'productName',
      ellipsis: true,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 4 : 1,
        };
      },
      // customRender: function (record, rowIndex) {
      //   return {  rowSpan: 0  }
      // }
      // onCell: (record) => ({rowSpan: 0})
    },
    {
      title: '规格',
      dataIndex: 'specifications',
      ellipsis: true,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '比重',
      dataIndex: 'specificWeight',
      ellipsis: true,
      width: 100,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '用量',
      dataIndex: 'usagee',
      ellipsis: true,
      width: 100,
      customCell: (record, rowIndex) => {
        return {
          colSpan: record.type === 2 ? 0 : 1,
        };
      },
    },
    {
      title: '单价',
      dataIndex: 'unitPrice',
      ellipsis: true,
      width: 100,
    },
    {
      title: '金额',
      dataIndex: 'sumOfMoney',
      ellipsis: true,
      width: 100,
    },
    {
      title: '备注',
      dataIndex: 'remark',
      ellipsis: true,
    }
  ]);

  // 表格加载loading
  const tableLoading = ref(false);
  // 表格数据
  const tableData = ref([]);
  // 总数
  const total = ref(0);

  async function queryItems() {
    tableLoading.value = true;
    try {
      let queryResult = await quotationTemplateApi.queryItemsById(templateId);
      tableData.value = queryResult.data;
      initPricingType()
      // total.value = queryResult.data.total;
    } catch (e) {
      smartSentry.captureError(e);
    } finally {
      tableLoading.value = false;
    }
  }

  // 选择表格行
  const selectedRowKeyList = ref([]);

  function onSelectChange(selectedRowKeys) {
    selectedRowKeyList.value = selectedRowKeys;
  }

  function getCheckboxProps(record) {
    return {
      disabled: record.type !== 1 && record.type !== 3, // 不是主材或配件无法选中删除
      name: record.type,
    }
  }
  // 添加主材/配件
  function addItem(type) {
    let index
    if (type === 1) {
      index = tableData.value.findIndex(item => item.type === 2)
    } else {
      index = tableData.value.findIndex(item => item.type === 4)
    }
    if (index != -1) {
      let obj = {
        templateId: templateId,
        serialNumber: index+1,
        productName: "",
        specifications: "",
        specificWeight: null,
        usagee: null,
        unitPrice: null,
        sumOfMoney: null,
        remark: "",
        type: type,
        disabledFlag: 0,
      }
      tableData.value.splice(index, 0, obj)
    } else {
      message.error('添加失败,请联系管理员!');
    }
  }
  const map = new Map([
    [0, "元/米"],
    [3, "元/平方米"],
    [1, "元/个"],
    [2, "元/套"],
  ])
  // 更具报价方式, 更新单位
  function initPricingType() {
    let type = quotationDetail.pricingType
    if (type) {
      let unit = map.get(type)
      if (tableData.value[tableData.value.length - 1] !== unit) {
        for (let i = 0; i < tableData.value.length; i++) {
          if (tableData.value[i].type > 4) {
            tableData.value[i].specifications = unit
          }
        }
      }
    }
  }

  async function onSubmit() {
    await update()

  }

  async function update() {
    SmartLoading.show();
    try {
      let detail = {
        templateId: templateId,
        list: tableData.value,
      }
      await quotationTemplateApi.editItems(detail);
      message.success('操作成功');
      onClose();
    } catch (err) {
      smartSentry.captureError(err);
    } finally {
      SmartLoading.hide();
    }
  }

  function onDelete() {
    selectedRowKeyList.value.sort((a,b) => b-a) // 降序
    for (let i = 0; i < selectedRowKeyList.value.length; i++) {
      let index = selectedRowKeyList.value[i]
      tableData.value.splice(index, 1)
    }
    selectedRowKeyList.value = []
  }

  function handleInputChange(value, index) {
    let record = tableData.value[index]
    if (record.type === 1 && record.specificWeight != null && record.usagee != null && record.unitPrice != null) {
      tableData.value[index].sumOfMoney = record.specificWeight * record.usagee * record.unitPrice
    } else if (record.type === 3 && record.usagee != null && record.unitPrice != null) {
      tableData.value[index].sumOfMoney = record.usagee * record.unitPrice
    }
  }

  defineExpose({
    show,
  });
</script>

<style scoped lang="less">
  .form-item-no-margin{
    margin-bottom: 0;
  }
</style>